/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jsf.beans.admin;

import JDBCUtil.MyConn;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Danh
 */
@ManagedBean
@SessionScoped
public class loginBean {

    private String errorMessage;
    public Boolean isLoggedIn = false;
    Connection conn = null;
    private String username;
    private String password;

    public loginBean(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    public Boolean getIsLoggedIn() {
        return isLoggedIn;
    }

    public void setIsLoggedIn(Boolean isLoggedIn) {
        this.isLoggedIn = isLoggedIn;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public loginBean() {
        try {
            conn = MyConn.getConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public String checkLogin() {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(true);

        try {
            PreparedStatement pstmt = conn.prepareStatement("SELECT User_Name,User_Password,Account_Role FROM Accounts WHERE User_Name=? AND User_Password=? AND Account_Role='Admin'");
            pstmt.setString(1, this.username);
            pstmt.setString(2, this.password);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                session.setAttribute("user", username);
                setIsLoggedIn(true);
                return "home.xhtml";
            } else {
                errorMessage = "Invalid Username or Password.";
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        return "login.xhtml?faces-redirect=true";
    }

    public String logOut() {
        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
        setIsLoggedIn(false);
        setUsername("");
        setPassword("");
        return "login.xhtml?faces-redirect=true";
    }
}
